module Reports

  protected

  # sends a request to the reports server
  # passing a report name, a xml data source and an extra params hash
  # example: generate_report "atividades", "bizzdocs/root/enterprisey/activities", @atividades.to_xml
  # OPTIMIZE mover pra Module, incluir apenas nos controllers que usarem
  def generate_report(report, path, xml = nil, params = nil, ignore_cache = true)
    return if report.blank? or path.blank?
    output_path = full_report_path(path)
    build_report(report, output_path, xml, params) if ignore_cache or !File.exists?(output_path)
    send_report(output_path)
  rescue RuntimeError => error
    flash[:error] = error.message
    redirect_to :back
  end

  private

  def build_report(reports, output_path, data = nil, params = nil)
    report_params = { :reports => [*reports].join(";"), :org => APP_CONFIG['org'], :path => output_path }
    report_params[:data] = data  if data
    report_params.merge!(params) if params.try(:is_a?, Hash)

    res = Net::HTTP.post_form(reports_service_url, report_params)

    logger.debug "ReportServer: HTTP #{res.code} #{res.message} - #{res.body}"

    unless res.body.include? "SUCCESS"
      raise RuntimeError, "Falha ao gerar documento requisitado, favor entrar em contato com o suporte."
    end
  rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH, Errno::ENOTCONN, Timeout::Error
    logger.error "ReportServer: OFFLINE"
    raise RuntimeError, "Falha ao acessar servidor de documentos, favor tentar novamente mais tarde."
  end

  def send_report(path)
    # OPTIMIZE :x_sendfile => true (apache mod_xsendfile)
    send_file path, :type => "application/pdf", :disposition => 'inline'
  end

  def reports_service_url
    @reports_service_url ||= URI.parse(APP_CONFIG['reports_url'])
  end

  def full_report_path(path)
    Rails.root.join "assets", "documentos", "#{path}.pdf"
  end

end